package com.example.peibei.ui.fragment;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dingtao.common.bean.HomeCateTwo;
import com.dingtao.common.bean.PaiDanList;
import com.dingtao.common.bean.User;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDFragment;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.CityList;
import com.example.peibei.service.presenter.HomeBannerCatePresenter;
import com.example.peibei.service.presenter.PaiDanListPresenter;
import com.example.peibei.ui.activity.LoginActivity;
import com.example.peibei.ui.activity.MemberActivity;
import com.example.peibei.ui.activity.PaiDanDetailActivity;
import com.example.peibei.ui.adapter.CityListAdapter;
import com.example.peibei.ui.adapter.PaiDanListAdapter;
import com.example.peibei.ui.weight.EmptyRecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PaiDanFragment extends WDFragment {
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll_one)
    LinearLayout ll_one;
    @BindView(R.id.tv_cate_one)
    TextView tv_cate_one;
    @BindView(R.id.tv_cate_three)
    TextView tv_cate_three;

    private PaiDanListPresenter paiDanListPresenter;
    private PaiDanListAdapter adapter;
    private String cityCode = "";
    private String categoryId = "";
    private String sortPrice = "";
    private SPUtils spUtils;

    @Override
    public String getPageName() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_pai_dan;
    }

    @Override
    protected void initView() {
        spUtils = new SPUtils(getActivity(), SpConstant.USER_TOKEN);
        adapter = new PaiDanListAdapter();
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String token = spUtils.getString(SpConstant.USER_TOKEN);
                if (TextUtils.isEmpty(token)){
                    intent(LoginActivity.class);
                    return;
                }
                PaiDanList.RecordsDTO data = (PaiDanList.RecordsDTO)adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putString("paidanId", data.getId());
                intent(PaiDanDetailActivity.class, bundle);
            }
        });
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                onRefreshStart();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                onLoadData();
            }
        });

        paiDanListPresenter = new PaiDanListPresenter(new OrderCall());
        paiDanListPresenter.reqeust(true, categoryId, cityCode, sortPrice);

    }

    public void onRefreshStart() {
        paiDanListPresenter.reqeust(true, categoryId, cityCode, sortPrice);
    }

    public void onLoadData(){
        paiDanListPresenter.reqeust(false, categoryId, cityCode, sortPrice);
    }

    class OrderCall implements DataCall<PaiDanList> {

        View view;

        @Override
        public void success(PaiDanList data, Object... args) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            //添加列表并刷新
            if (paiDanListPresenter.getPage() == 1) {
                adapter.setNewInstance(data.getRecords());
            }else {
                adapter.addData(data.getRecords());
            }
            if (adapter.getData().isEmpty()){
                view = LayoutInflater.from(getContext()).inflate(R.layout.empty_home_child,null,false);
                adapter.setFooterView(view);
            }else {
                if (view != null)
                    adapter.removeFooterView(view);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            refreshLayout.finishRefresh(true);
        }
    }

    @OnClick(R.id.ll_one)
    public void chooseOne() {
        User loginUser = SpConstant.getLoginUser();
        if (!loginUser.isVip()){
            intent(MemberActivity.class);
            return;
        }
        showCityList();
    }

    private void showCityList(){
        StringBuffer sb =new StringBuffer();
        try {
            InputStream open = getActivity().getAssets().open("city3.json");
            byte[] b = new byte[open.available()];
            int len;
            while ((len = open.read(b))!= -1){
                sb.append(new String(b,0,len));
            }
            open.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<CityList> list = new Gson().fromJson(sb.toString(),new TypeToken<List<CityList>>(){}.getType());
        CityList all = new CityList();
        all.setAreaName("全部");
        list.add(0,all);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.pup_city_list,null,false);
        RecyclerView rv1 = view.findViewById(R.id.rv1);
        RecyclerView rv2 = view.findViewById(R.id.rv2);
        rv1.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv2.setLayoutManager(new LinearLayoutManager(getActivity()));
        CityListAdapter adapter1 = new CityListAdapter(list);
        rv1.setAdapter(adapter1);
        PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, DensityUtil.dp2px(393));
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(ll_one);
        adapter1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> a, @NonNull View view, int position) {
                if (position == 0){
                    popupWindow.dismiss();
                    CityList item = adapter1.getItem(position);
                    String cityName = item.getAreaName();
                    cityCode = "";
                    tv_cate_one.setText(cityName);
                    onRefreshStart();
                    return;
                }
                CityListAdapter adapter = new CityListAdapter(adapter1.getItem(position).getCities());
                rv2.setAdapter(adapter);
                adapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> a, @NonNull View view, int position) {
                        popupWindow.dismiss();
                        CityList item = adapter.getItem(position);
                        String cityName = item.getAreaName();
                        cityCode = item.getAreaId();
                        tv_cate_one.setText(cityName);
                        onRefreshStart();
                    }
                });
            }
        });
    }

    private void showChooseThree(){
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.pup_paidan,null,false);
        TextView tv_asc = view.findViewById(R.id.tv_asc);
        TextView tv_desc = view.findViewById(R.id.tv_desc);

        if ("1".equals(sortPrice)){
            tv_desc.setTextColor(Color.WHITE);
            tv_desc.setBackgroundResource(R.drawable.shape_49696_radius8);
            tv_asc.setTextColor(Color.parseColor("#80000000"));
            tv_asc.setBackgroundResource(R.drawable.shape_1a000_radius8);
        }else {
            tv_asc.setTextColor(Color.WHITE);
            tv_asc.setBackgroundResource(R.drawable.shape_49696_radius8);
            tv_desc.setTextColor(Color.parseColor("#80000000"));
            tv_desc.setBackgroundResource(R.drawable.shape_1a000_radius8);
        }

        PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(ll_one);

        tv_asc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                tv_cate_three.setText("价格从低到高");
                sortPrice = "0";
                onRefreshStart();
            }
        });
        tv_desc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                tv_cate_three.setText("价格从高到低");
                sortPrice = "1";
                onRefreshStart();
            }
        });
    }


    @OnClick(R.id.ll_three)
    public void chooseThree() {
        User loginUser = SpConstant.getLoginUser();
        if (!loginUser.isVip()){
            intent(MemberActivity.class);
            return;
        }
        showChooseThree();
    }
}
